package com.meteor.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.meteor.api.feign.system.SystemFeign;
import com.meteor.api.feign.system.dto.SysMerchantDTO;
import com.meteor.convert.BuildingConvert;
import com.meteor.convert.VisitorConvert;
import com.meteor.entity.Building;
import com.meteor.entity.Community;
import com.meteor.entity.Visitor;
import com.meteor.framework.common.base.ResponseData;
import com.meteor.framework.common.constant.Constant;
import com.meteor.framework.common.enums.UserAdminEnum;
import com.meteor.framework.common.exception.ServerException;
import com.meteor.framework.common.utils.PageResult;
import com.meteor.framework.mybatis.service.impl.BaseServiceImpl;
import com.meteor.framework.security.user.SecurityUser;
import com.meteor.mapper.BuildingMapper;
import com.meteor.mapper.VisitorMapper;
import com.meteor.query.BuildingQuery;
import com.meteor.query.VisitorQuery;
import com.meteor.service.BuildingService;
import com.meteor.service.CommunityService;
import com.meteor.service.VisitorService;
import com.meteor.vo.BuildingVO;
import com.meteor.vo.CommunityVO;
import com.meteor.vo.VisitorVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lynn
 * @date 2024/1/22
 */


@Service
@AllArgsConstructor
public class VisitorServiceImpl extends BaseServiceImpl<VisitorMapper, Visitor> implements VisitorService {


    private final SystemFeign systemFeign;

    private final CommunityService communityService;


    @Override
    public void save(VisitorVO vo) {
        Visitor  entity= VisitorConvert.INSTANCE.convert(vo);

        if(!SecurityUser.getUser().getUsername().equalsIgnoreCase(UserAdminEnum.ADMIN.getValue())){

            if(ObjectUtils.isEmpty(vo.getOrgId())){
                entity.setOrgId(SecurityUser.getUser().getOrgId());
            }
            LambdaQueryWrapper<Community> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(StrUtil.isNotBlank(vo.getOrgId()),Community::getOrgId, vo.getOrgId());
            wrapper.eq(StrUtil.isNotBlank(vo.getCommunityId()),Community::getId, vo.getCommunityId());
            wrapper.eq(Community::getDeleted,0);
            Community community = communityService.getOne(wrapper);
            if(ObjectUtils.isEmpty(community)){
                throw new ServerException("该社区不存在");
            }
            entity.setCommunityId(community.getId());

        }else{

            if(ObjectUtils.isEmpty(vo.getCommunityId())) {
                throw new ServerException("请选择社区");
            }

            CommunityVO communityVO = communityService.getCommunity(vo.getCommunityId());
            if(ObjectUtils.isEmpty(communityVO)){
                throw new ServerException("该社区不存在");
            }
            vo.setOrgId(communityVO.getOrgId());

            ResponseData responseData = JSON.parseObject(systemFeign.orgMerchant(vo.getOrgId()),ResponseData.class);
            if(!ObjectUtils.isEmpty(responseData.getData())){
                SysMerchantDTO sysMerchantDTO = JSON.parseObject(responseData.getData().toString(),SysMerchantDTO.class);
                entity.setMerchantId(sysMerchantDTO.getId());
            }
            entity.setOrgId(vo.getOrgId());
            /*if(ObjectUtils.isEmpty(vo.getMerchantId())) {
                throw new ServerException("请选择商户");
            }*/
        }

//        entity.setMerchantId(SecurityUser.getUser().getMerchantId());
//        entity.setOrgId(SecurityUser.getUser().getOrgId());

        baseMapper.insert(entity);
    }

    @Override
    public void update(VisitorVO vo) {
        Visitor visitor = VisitorConvert.INSTANCE.convert(vo);
        if (ObjectUtils.isEmpty(visitor.getId())) {
            throw new ServerException("修改失败，id为空");
        }
        baseMapper.updateById(visitor);

    }

    @Override
    public VisitorVO get(String id) {
        return VisitorConvert.INSTANCE.convert(baseMapper.selectById(id));
    }

    @Override
    public List<VisitorVO> getList(VisitorQuery query) {

        LambdaQueryWrapper<Visitor> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getVisitorName()), Visitor::getVisitorName, query.getVisitorName());
        wrapper.eq(StrUtil.isNotBlank(query.getVisitorName()), Visitor::getVisitorPhoneNumber, query.getVisitorPhoneNumber());
        wrapper.eq(StrUtil.isNotBlank(query.getCommunityId()), Visitor::getCommunityId, query.getCommunityId());

        List<Visitor> complaints = baseMapper.selectList(wrapper);

        return VisitorConvert.INSTANCE.convertList(complaints);
    }

    @Override
    public PageResult<VisitorVO> page(VisitorQuery query) {

        // 查询参数
        Map<String, Object> params = getParams(query);

        // 分页查询
        IPage<Visitor> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<VisitorVO> list = baseMapper.getList(params);

        return new PageResult<>(list, page.getTotal());

//        IPage<Complaint> page = baseMapper.selectPage(getPage(query), getWrapper(query));
//
//        return new PageResult<ComplaintVO>(ComplaintConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    @Override
    public void delete(String id) {
        removeById(id);
    }

    @Override
    public PageResult<VisitorVO> getUserId(VisitorQuery query) {
        // 查询参数
        Map<String, Object> params = getParamsNOAuth(query);

        // 分页查询
        IPage<Visitor> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<VisitorVO> list = baseMapper.getList(params);

        return new PageResult<>(list, page.getTotal());
    }

    private Map<String, Object> getParams(VisitorQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("visitorName", query.getVisitorName());
        params.put("visitorPhoneNumber", query.getVisitorPhoneNumber());
        params.put("communityId", query.getCommunityId());

        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope("t1", null,"pf_visitor"));

        return params;
    }

    private Map<String, Object> getParamsNOAuth(VisitorQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("visitorName", query.getVisitorName());
        params.put("visitorPhoneNumber", query.getVisitorPhoneNumber());
        params.put("communityId", query.getCommunityId());
        params.put("userId", query.getUserId());


        return params;
    }

    private Wrapper<Visitor> getWrapper(VisitorQuery query){
        LambdaQueryWrapper<Visitor> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getVisitorName()), Visitor::getVisitorName, query.getVisitorName());
        wrapper.eq(StrUtil.isNotBlank(query.getVisitorPhoneNumber()), Visitor::getVisitorPhoneNumber, query.getVisitorPhoneNumber());
        wrapper.eq(StrUtil.isNotBlank(query.getCommunityId()), Visitor::getCommunityId, query.getCommunityId());

        // 数据权限
        dataScopeWrapper(wrapper);

        return wrapper;
    }
}
